package com.axend.aerosense.dev.fragment.checkupdate;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.activity.NewDevSetNetActivity;
import com.axend.aerosense.dev.databinding.DevFragmentUpdateTaskBinding;
import com.axend.aerosense.dev.impl.IBack;
import com.axend.aerosense.dev.viewmodel.UpdateTaskViewModel;

/**
 * @author ChenHongWei
 * @date :2021/1/12 17:40
 */

public class DevDeviceUpdateTaskFragment extends MvvmBaseFragment<DevFragmentUpdateTaskBinding, UpdateTaskViewModel> {

//    private FirmwareUpdate firmwareUpdate;
//    private static boolean isInit = true;  //是否第一次初始化
//    private boolean isUpdateSuccess = false;  //升级是否成功

    public static DevDeviceUpdateTaskFragment getInstance(){
        DevDeviceUpdateTaskFragment fragment = new DevDeviceUpdateTaskFragment();
        return fragment;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();
    }

    private void initView(){
        Bundle bundle = getArguments();
        if (null != bundle){
            boolean isSuccess = bundle.getBoolean(DevCheckUpdateFragment.UPGRADE_RESULT, false);
            viewModel.isSuccess.setValue(isSuccess);
            viewDataBinding.devImageBg.setImageResource(isSuccess ? R.mipmap.dev_icon_successfully_updated : R.mipmap.dev_icon_update_failed);
        }

        ((NewDevSetNetActivity)getActivity()).setiBack(() -> {
            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.DEV_COUNT_CHANGE, Integer.class).postValue(1);
            // 返回到第一Fragment
            FragmentManager.BackStackEntry entry = getActivity().getSupportFragmentManager().getBackStackEntryAt(0);
            int id = entry.getId();
            getActivity().getSupportFragmentManager().popBackStack(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            return true;
        });

//        firmwareUpdate = new FirmwareUpdate();
//        firmwareUpdate.setCallback(new FirmwareUpdate.UpdateStatusCallback() {
//            @Override
//            public void status(int statusCode) {
//                LogUtils.d(DevDeviceUpdateTaskFragment.this, "statusCode:" + statusCode);
//                getActivity().runOnUiThread(() -> {
//                    if (statusCode == FirmwareUpdate.STATUS_READY) {
//                        firmwareUpdate.startUpdate();
//                        viewDataBinding.devTextTip.setText(R.string.dev_update_now_warning_tip);
//                    } else if (statusCode == FirmwareUpdate.STATUS_UPDATE_SUCCESS) {
//                        viewDataBinding.devBtnBottm.setVisibility(View.VISIBLE);
//                        viewDataBinding.devConstraintlayoutProgress.setVisibility(View.GONE);
//                        String firmwareVersionNum = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.FIRMWARE_VERSION_NUM, "");
//                        String text = String.format(getString(R.string.dev_update_success_tip), firmwareVersionNum);
//                        com.blankj.utilcode.util.LogUtils.d(text, firmwareVersionNum);
//                        viewDataBinding.devTextTip.setText(text);
//                        viewDataBinding.devBtnBottm.setText(R.string.dev_complete);
//                        isUpdateSuccess = true;
//                        //((DevBaseWifiActivity) getActivity()).closeDeviceConnect();
//                    } else if (statusCode == FirmwareUpdate.STATUS_DEVICE_UNCONNECTED
//                            || statusCode == FirmwareUpdate.STATUS_CONNECT_EXCEPTION
//                            || statusCode == FirmwareUpdate.FILE_NOT_FOUND
//                            || statusCode == FirmwareUpdate.STATUS_UPDATE_EXCEPTION) {
//                        if (!isUpdateSuccess) {
//                            viewDataBinding.devBtnBottm.setVisibility(View.VISIBLE);
//                            viewDataBinding.devConstraintlayoutProgress.setVisibility(View.GONE);
//                            viewDataBinding.devTextTip.setText(R.string.dev_update_failure);
//                            viewDataBinding.devBtnBottm.setText(R.string.dev_back_setting);
//                            isUpdateSuccess = false;
//                        }
//                        //((DevBaseWifiActivity) getActivity()).closeDeviceConnect();
//                    }
//                });
//            }
//
//            @Override
//            public void progress(float progress) {
//                //更新进度条
//                int temp = (int) (progress * 100);
//               viewModel.count.postValue(temp);
//               viewModel.btnText.postValue(getString(R.string.dev_updating) + "  " + temp + "%");
//            }
//        });
//
//        viewDataBinding.devBtnBottm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isInit){
//                    //禁用返回
//                    ((NewDevSetNetActivity) getActivity()).enableBack(false);
//                    firmwareUpdate.init();
//                    viewDataBinding.devBtnBottm.setVisibility(View.GONE);
//                    viewDataBinding.devConstraintlayoutProgress.setVisibility(View.VISIBLE);
//                    viewDataBinding.devProgressbarTip.setText(R.string.dev_ready_update_now);
//                    isInit = false;
//                    isScreenAlwaysLight(true);
//                }else {
//                    //启用返回功能
//                    ((NewDevSetNetActivity) getActivity()).enableBack(true);
//                    isInit = true;
//                    cleanMd5();
//                    isScreenAlwaysLight(false);
////                    FragmentManager.BackStackEntry entry = getActivity().getSupportFragmentManager().getBackStackEntryAt(0);
////                    int id = entry.getId();
////                    getActivity().getSupportFragmentManager().popBackStack(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
////                    FragmentUtils.show(getActivity().getSupportFragmentManager());
//                    getActivity().finish();
//                }
//            }
//        });

    }

    private void cleanMd5(){
        MmkvHelper.getInstance()
                .getMmkv()
                .remove(Gobal.SAVE_KEY.BIN_FILE_MD5);
        MmkvHelper.getInstance()
                .getMmkv()
                .remove(Gobal.SAVE_KEY.FIRMWARE_VERSION_NUM);
    }

    /** 屏幕是否常亮 */
    private void isScreenAlwaysLight(boolean bool){
        if (bool){
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }else {
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //设置标题
        ((ITitle)getActivity()).setTitle(getString(R.string.dev_update));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 记得销毁此回调
        ((NewDevSetNetActivity)getActivity()).setiBack(null);
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_update_task;
    }

    @Override
    public int getBindingVariable() {
        return BR.viewmodel;
    }

    @Override
    protected UpdateTaskViewModel getViewModel() {
        return new ViewModelProvider(this).get(UpdateTaskViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {

    }
}
